package org.voyager.service.wx.service.impl;

import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.voyager.service.wx.dao.WechatUserDao;
import org.voyager.service.wx.domain.WechatUserPO;
import org.voyager.service.wx.service.WechatUserservice;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;

@Service
public class WechatUserServiceImpl implements WechatUserservice {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WechatUserDao wechatUserDao;

    @Async
    @Override
    public void saveWxUser(WxMpUser userWxInfo) {
        WechatUserPO po = new WechatUserPO();
        BeanUtils.copyProperties(userWxInfo, po);

        Instant instant = Instant.ofEpochSecond(userWxInfo.getSubscribeTime());
        ZoneId zone = ZoneId.systemDefault();
        po.setSubscribeTime(LocalDateTime.ofInstant(instant, zone));

        po.setTagIds(Arrays.toString(userWxInfo.getTagIds()));
        po.setPrivileges(Arrays.toString(userWxInfo.getPrivileges()));

        int i = wechatUserDao.mergeUser(po);
        logger.info("mergeUser count: {}", i);
    }

    @Override
    public void unsubscribe(String openId) {
        wechatUserDao.unsubscribe(openId);
    }
}
